package ru.zombator.taskman.dbadmin.actions;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;

import ru.zombator.taskman.core.dbclient.IDbClient.Role;
import ru.zombator.taskman.dbadmin.AdminApp;
import ru.zombator.taskman.dbadmin.ImageNames;
import ru.zombator.taskman.dbadmin.dialogs.AddEditUserDialog;
import ru.zombator.taskman.dbadmin.dialogs.AddEditUserDialog.Mode;

public class AddUserAction extends ASimpleAction {
	private static final String ACTION_ID = "ru.zombator.taskman.dbadmin.addUser";
	
	@Override
	public String getId() {
		return ACTION_ID;
	}
	
	public AddUserAction(AdminApp mainApp) {
		super(mainApp);
	}
	
	@Override
	protected String getImageName() {
		return ImageNames.ADD_USER;
	}
	
	@Override
	public String getText() {
		return "Добавить...";
	}
	
	@Override
	public void run() {
		AddEditUserDialog dialog = new AddEditUserDialog(mainApp,
				Mode.ADDING);
		if (dialog.open() == IDialogConstants.OK_ID) {
			final String ipAddress = dialog.getIpAddress();
			final String name = dialog.getUserName();
			final Role role = dialog.getRole();
			
			try {
				AddUserTask addTask = new AddUserTask(mainApp, name, ipAddress, role);
				new ProgressMonitorDialog(mainApp.getShell()).run(true, false, addTask);
				mainApp.getLocalUserList().add(addTask.getNewPerson());
				mainApp.getUsersTable().setInput(mainApp.getLocalUserList());
			} catch (InvocationTargetException e) {
				e.printStackTrace();
				MessageDialog.openError(mainApp.getShell(), "Ошибка",
						e.getCause().getMessage() != null ? e.getCause().getMessage() :
							"Не удалось создать пользователя.");
			} catch (InterruptedException e) {
				// non-cancelable => это исключение не возникнет
			}
		}
	}
}
